// Vue 3 组件化 TodoList 应用
// 开发团队：5人小组项目

const { createApp, ref, reactive, computed, onMounted } = Vue;

// 数据存储服务 - 开发者：彭鸿润
const useTodoStore = () => {
  const data = reactive({
    todo: [],
    completed: []
  });

  // 从localStorage加载数据
  const loadData = () => {
    const stored = localStorage.getItem('todoList');
    if (stored) {
      const parsed = JSON.parse(stored);
      data.todo = parsed.todo || [];
      data.completed = parsed.completed || [];
    }
  };

  // 保存数据到localStorage
  const saveData = () => {
    localStorage.setItem('todoList', JSON.stringify(data));
  };

  // 添加待办事项
  const addTodo = (text) => {
    if (text.trim()) {
      data.todo.unshift(text.trim());
      saveData();
    }
  };

  // 删除待办事项
  const removeTodo = (index, isCompleted = false) => {
    if (isCompleted) {
      data.completed.splice(index, 1);
    } else {
      data.todo.splice(index, 1);
    }
    saveData();
  };

  // 完成/取消完成待办事项
  const toggleComplete = (index, isCompleted = false) => {
    if (isCompleted) {
      const item = data.completed.splice(index, 1)[0];
      data.todo.unshift(item);
    } else {
      const item = data.todo.splice(index, 1)[0];
      data.completed.unshift(item);
    }
    saveData();
  };

  return {
    data,
    loadData,
    saveData,
    addTodo,
    removeTodo,
    toggleComplete
  };
};

// TodoHeader 组件 - 开发者：余亚涛
const TodoHeader = {
  template: `
    <header>
      <input 
        type="text" 
        placeholder="Enter an activity.." 
        v-model="newTodo"
        @keydown.enter="handleAdd"
        ref="inputRef"
      >
      <button @click="handleAdd">
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"viewBox="0 0 16 16" style="enable-background:new 0 0 16 16;" xml:space="preserve"><g><path class="fill" d="M16,8c0,0.5-0.5,1-1,1H9v6c0,0.5-0.5,1-1,1s-1-0.5-1-1V9H1C0.5,9,0,8.5,0,8s0.5-1,1-1h6V1c0-0.5,0.5-1,1-1s1,0.5,1,1v6h6C15.5,7,16,7.5,16,8z"/></g></svg>
      </button>
    </header>
  `,
  setup(props, { emit }) {
    const newTodo = ref('');
    const inputRef = ref(null);

    const handleAdd = () => {
      if (newTodo.value.trim()) {
        emit('add-todo', newTodo.value);
        newTodo.value = '';
        inputRef.value?.focus();
      }
    };

    return {
      newTodo,
      inputRef,
      handleAdd
    };
  }
};

// TodoItem 组件 - 开发者：王辉
const TodoItem = {
  template: `
    <li>
      {{ text }}
      <div class="buttons">
        <button class="remove" @click="handleRemove">
          <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 22 22" style="enable-background:new 0 0 22 22;" xml:space="preserve"><rect class="noFill" width="22" height="22"/><g><g><path class="fill" d="M16.1,3.6h-1.9V3.3c0-1.3-1-2.3-2.3-2.3h-1.7C8.9,1,7.8,2,7.8,3.3v0.2H5.9c-1.3,0-2.3,1-2.3,2.3v1.3c0,0.5,0.4,0.9,0.9,1v10.5c0,1.3,1,2.3,2.3,2.3h8.5c1.3,0,2.3-1,2.3-2.3V8.2c0.5-0.1,0.9-0.5,0.9-1V5.9C18.4,4.6,17.4,3.6,16.1,3.6z M9.1,3.3c0-0.6,0.5-1.1,1.1-1.1h1.7c0.6,0,1.1,0.5,1.1,1.1v0.2H9.1V3.3z M16.3,18.7c0,0.6-0.5,1.1-1.1,1.1H6.7c-0.6,0-1.1-0.5-1.1-1.1V8.2h10.6V18.7z M17.2,7H4.8V5.9c0-0.6,0.5-1.1,1.1-1.1h10.2c0.6,0,1.1,0.5,1.1,1.1V7z"/></g><g><g><path class="fill" d="M11,18c-0.4,0-0.6-0.3-0.6-0.6v-6.8c0-0.4,0.3-0.6,0.6-0.6s0.6,0.3,0.6,0.6v6.8C11.6,17.7,11.4,18,11,18z"/></g><g><path class="fill" d="M8,18c-0.4,0-0.6-0.3-0.6-0.6v-6.8c0-0.4,0.3-0.6,0.6-0.6c0.4,0,0.6,0.3,0.6,0.6v6.8C8.7,17.7,8.4,18,8,18z"/></g><g><path class="fill" d="M14,18c-0.4,0-0.6-0.3-0.6-0.6v-6.8c0-0.4,0.3-0.6,0.6-0.6c0.4,0,0.6,0.3,0.6,0.6v6.8C14.6,17.7,14.3,18,14,18z"/></g></g></g></svg>
        </button>
        <button class="complete" @click="handleToggle">
          <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 22 22" style="enable-background:new 0 0 22 22;" xml:space="preserve"><rect y="0" class="noFill" width="22" height="22"/><g><path class="fill" d="M9.7,14.4L9.7,14.4c-0.2,0-0.4-0.1-0.5-0.2l-2.7-2.7c-0.3-0.3-0.3-0.8,0-1.1s0.8-0.3,1.1,0l2.1,2.1l4.8-4.8c0.3-0.3,0.8-0.3,1.1,0s0.3,0.8,0,1.1l-5.3,5.3C10.1,14.3,9.9,14.4,9.7,14.4z"/></g></svg>
        </button>
      </div>
    </li>
  `,
  props: {
    text: String,
    index: Number,
    isCompleted: Boolean
  },
  emits: ['remove', 'toggle'],
  setup(props, { emit }) {
    const handleRemove = () => {
      emit('remove', props.index, props.isCompleted);
    };

    const handleToggle = () => {
      emit('toggle', props.index, props.isCompleted);
    };

    return {
      handleRemove,
      handleToggle
    };
  }
};

// TodoList 组件 - 开发者：罗豪
const TodoList = {
  template: `
    <ul class="todo" id="todo">
      <todo-item
        v-for="(item, index) in todos"
        :key="'todo-' + index"
        :text="item"
        :index="index"
        :is-completed="false"
        @remove="handleRemove"
        @toggle="handleToggle"
      />
    </ul>
  `,
  components: {
    TodoItem
  },
  props: {
    todos: Array
  },
  emits: ['remove', 'toggle'],
  setup(props, { emit }) {
    const handleRemove = (index, isCompleted) => {
      emit('remove', index, isCompleted);
    };

    const handleToggle = (index, isCompleted) => {
      emit('toggle', index, isCompleted);
    };

    return {
      handleRemove,
      handleToggle
    };
  }
};

// CompletedList 组件 - 开发者：冉帅
const CompletedList = {
  template: `
    <ul class="todo" id="completed">
      <todo-item
        v-for="(item, index) in completed"
        :key="'completed-' + index"
        :text="item"
        :index="index"
        :is-completed="true"
        @remove="handleRemove"
        @toggle="handleToggle"
      />
    </ul>
  `,
  components: {
    TodoItem
  },
  props: {
    completed: Array
  },
  emits: ['remove', 'toggle'],
  setup(props, { emit }) {
    const handleRemove = (index, isCompleted) => {
      emit('remove', index, isCompleted);
    };

    const handleToggle = (index, isCompleted) => {
      emit('toggle', index, isCompleted);
    };

    return {
      handleRemove,
      handleToggle
    };
  }
};

// 用户认证组件 - 开发者：彭鸿润
const AuthComponent = {
  template: `
    <div v-if="!isLoggedIn" class="auth-container">
      <div class="auth-form">
        <h2>{{ isLogin ? '登录' : '注册' }}</h2>
        <input 
          v-model="username" 
          type="text" 
          placeholder="用户名"
          @keydown.enter="handleSubmit"
        >
        <input 
          v-model="password" 
          type="password" 
          placeholder="密码"
          @keydown.enter="handleSubmit"
        >
        <button @click="handleSubmit">
          {{ isLogin ? '登录' : '注册' }}
        </button>
        <button @click="toggleMode" class="toggle-btn">
          {{ isLogin ? '切换到注册' : '切换到登录' }}
        </button>
      </div>
    </div>
  `,
  setup(props, { emit }) {
    const isLoggedIn = ref(false);
    const isLogin = ref(true);
    const username = ref('');
    const password = ref('');

    const toggleMode = () => {
      isLogin.value = !isLogin.value;
    };

    const handleSubmit = () => {
      if (!username.value.trim() || !password.value.trim()) {
        alert('请输入用户名和密码');
        return;
      }

      if (isLogin.value) {
        // 登录逻辑
        const users = JSON.parse(localStorage.getItem('users') || '[]');
        const user = users.find(u => u.username === username.value && u.password === password.value);
        if (user) {
          isLoggedIn.value = true;
          emit('login-success', username.value);
        } else {
          alert('用户名或密码错误');
        }
      } else {
        // 注册逻辑
        const users = JSON.parse(localStorage.getItem('users') || '[]');
        if (users.find(u => u.username === username.value)) {
          alert('用户名已存在');
          return;
        }
        users.push({ username: username.value, password: password.value });
        localStorage.setItem('users', JSON.stringify(users));
        alert('注册成功，请登录');
        isLogin.value = true;
      }
    };

    return {
      isLoggedIn,
      isLogin,
      username,
      password,
      toggleMode,
      handleSubmit
    };
  }
};

// 主应用组件 - 开发者：余亚涛（整合）
const TodoApp = {
  template: `
    <div>
      <auth-component 
        v-if="!isLoggedIn" 
        @login-success="handleLoginSuccess"
      />
      <div v-else>
        <todo-header @add-todo="handleAddTodo" />
        <div class="container">
          <todo-list 
            :todos="todoStore.data.todo"
            @remove="handleRemove"
            @toggle="handleToggle"
          />
          <completed-list 
            :completed="todoStore.data.completed"
            @remove="handleRemove"
            @toggle="handleToggle"
          />
        </div>
        <!-- 欢迎弹窗 -->
        <div v-if="showWelcomePopup" class="welcome-popup" @click="closeWelcomePopup">
          <div class="welcome-popup-content" @click.stop>
            <h3>欢迎，{{ currentUser }}！</h3>
            <p>开始管理您的待办事项吧！</p>
            <button @click="closeWelcomePopup" class="close-btn">确定</button>
          </div>
        </div>
      </div>
    </div>
  `,
  components: {
    AuthComponent,
    TodoHeader,
    TodoList,
    CompletedList
  },
  setup() {
    const isLoggedIn = ref(false);
    const currentUser = ref('');
    const showWelcomePopup = ref(false);
    const todoStore = useTodoStore();

    const handleLoginSuccess = (username) => {
      isLoggedIn.value = true;
      currentUser.value = username;
      todoStore.loadData();
      // 显示欢迎弹窗
      showWelcomePopup.value = true;
    };

    const handleAddTodo = (text) => {
      todoStore.addTodo(text);
    };

    const handleRemove = (index, isCompleted) => {
      todoStore.removeTodo(index, isCompleted);
    };

    const handleToggle = (index, isCompleted) => {
      todoStore.toggleComplete(index, isCompleted);
    };

    const closeWelcomePopup = () => {
      showWelcomePopup.value = false;
    };

    return {
      isLoggedIn,
      currentUser,
      showWelcomePopup,
      todoStore,
      handleLoginSuccess,
      handleAddTodo,
      handleRemove,
      handleToggle,
      closeWelcomePopup
    };
  }
};

// 创建Vue应用 - 开发者：王辉（应用初始化）
const app = createApp(TodoApp);
app.mount('#app');